package cn.jingyuan.swan.cloud.dao.mybatisplus;

import cn.jingyuan.swan.cloud.dao.CrudDao;
import cn.jingyuan.swan.cloud.dao.DaoException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;

import java.io.Serializable;
import java.util.List;

/**
 * MyBatis-Plus 实现
 *
 * @param <E>  实体
 * @param <ID> 主键
 */
public abstract class AbstractMyBatisPlusCrudDao<E, ID extends Serializable> extends AbstractMyBatisPlusEmptyDao<E, ID> implements CrudDao<E, ID> {

    /** 操作不支持异常 */
    protected static final DaoException DAO_EX_NONSUPPORT = new DaoException("操作不支持");

    @Override
    public int insert(E entity) {
        return getMapper().insert(entity);
    }

    @Override
    public int inserts(List<E> entities) {
        int rows = 0;
        for (E entity : entities) {
            int row = getMapper().insert(entity);
            rows += row;
        }
        return rows;
    }

    @Override
    public int delete(ID id) {
        return getMapper().deleteById(id);
    }

    @Override
    public int deletes(List<ID> ids) {
        return getMapper().deleteBatchIds(ids);
    }

    @Override
    public int deleteAll() {
        return getMapper().delete(null);
    }

    @Override
    public int update(E entity) {
        return getMapper().updateById(entity);
    }

    @Override
    public int updates(List<E> entities) {
        int rows = 0;
        for (E t : entities) {
            int row = getMapper().updateById(t);
            rows += row;
        }
        return rows;
    }

    @Override
    public E get(ID id) {
        return getMapper().selectById(id);
    }

    @Override
    public List<E> gets(List<ID> ids) {
        return getMapper().selectBatchIds(ids);
    }

    @Override
    public List<E> getAll() {
        return getMapper().selectList(null);
    }

    @Override
    public int count() {
        return getMapper().selectCount(null);
    }

    @Override
    public int countOfIds(List<ID> ids) {
        return getMapper().selectBatchIds(ids).size();
    }

    protected LambdaQueryWrapper<E> queryWrapper() {
        return new LambdaQueryWrapper<>();
    }

    protected LambdaUpdateWrapper<E> updateWrapper() {
        return new LambdaUpdateWrapper<>();
    }

}
